/**
 * Store标准化工具脚本
 * 用于将现有Store标准化，添加必要的方法和错误处理
 */

const { standardizeGlobalStore, standardizeModuleStore, BaseStoreMethods } = require('./store_standardizer');

/**
 * 标准化Store的帮助函数
 * @param {string} storePath - Store文件路径
 * @param {string} storeName - Store名称
 * @param {string} type - Store类型 (global|module)
 * @param {string} moduleName - 如果是module类型，则需要提供模块名称
 * @returns {string} 标准化后的文件内容
 */
function standardizeStoreFile(storePath, storeName, type = 'global', moduleName = '') {
  try {
    // 读取文件
    const fs = require('fs');
    let content = fs.readFileSync(storePath, 'utf8');
    
    // 检查文件是否已包含标准化代码
    if (content.includes('standardizeGlobalStore') || content.includes('standardizeModuleStore')) {
      console.log(`[${storeName}] 已标准化，跳过`);
      return content;
    }
    
    // 1. 添加导入
    if (!content.includes('standardizeGlobalStore') && !content.includes('standardizeModuleStore')) {
      // 检查是ES6还是CommonJS导入风格
      if (content.includes('import ')) {
        // ES6风格
        if (type === 'global') {
          content = content.replace(
            /import\s+{([^}]+)}\s+from\s+['"]mobx-miniprogram['"];/,
            'import { $1 } from \'mobx-miniprogram\';\nimport { standardizeGlobalStore } from \'../helpers/store_standardizer.js\';'
          );
        } else {
          content = content.replace(
            /import\s+{([^}]+)}\s+from\s+['"]mobx-miniprogram['"];/,
            'import { $1 } from \'mobx-miniprogram\';\nimport { standardizeModuleStore } from \'../../helpers/store_standardizer.js\';'
          );
        }
      } else {
        // CommonJS风格
        if (type === 'global') {
          content = content.replace(
            /const\s+{([^}]+)}\s+=\s+require\(['"]mobx-miniprogram['"]\);/,
            'const { $1 } = require(\'mobx-miniprogram\');\nconst { standardizeGlobalStore } = require(\'../helpers/store_standardizer.js\');'
          );
        } else {
          content = content.replace(
            /const\s+{([^}]+)}\s+=\s+require\(['"]mobx-miniprogram['"]\);/,
            'const { $1 } = require(\'mobx-miniprogram\');\nconst { standardizeModuleStore } = require(\'../../helpers/store_standardizer.js\');'
          );
        }
      }
    }
    
    // 2. 查找Store定义
    const storeRegex = new RegExp(`export\\s+(?:const|let|var)\\s+${storeName}\\s*=\\s*observable\\(`);
    const storeMatch = content.match(storeRegex);
    
    if (!storeMatch) {
      console.error(`[${storeName}] 未找到Store定义`);
      return content;
    }
    
    // 3. 添加导出标准化Store
    if (content.match(/export\s+default\s+/)) {
      // 已有默认导出，替换它
      if (type === 'global') {
        content = content.replace(
          /export\s+default\s+[^;]+;?/,
          `export default standardizeGlobalStore(${storeName}, '${storeName}');`
        );
      } else {
        content = content.replace(
          /export\s+default\s+[^;]+;?/,
          `export default standardizeModuleStore(${storeName}, '${moduleName}', '${storeName}');`
        );
      }
    } else {
      // 无默认导出，添加一个
      if (type === 'global') {
        content += `\n\n// 应用标准化Store，确保拥有所有必要的方法和错误处理\nexport default standardizeGlobalStore(${storeName}, '${storeName}');`;
      } else {
        content += `\n\n// 应用标准化Store，确保拥有所有必要的方法和错误处理\nexport default standardizeModuleStore(${storeName}, '${moduleName}', '${storeName}');`;
      }
    }
    
    // 4. 确保有reset方法
    if (!content.includes('reset:') && !content.includes('reset =')) {
      // 查找Store对象结尾
      const storeEndMatch = content.match(/}\)\);/);
      if (storeEndMatch) {
        const endPosition = storeEndMatch.index;
        // 在Store结尾前添加reset方法
        const beforeEnd = content.substring(0, endPosition);
        const afterEnd = content.substring(endPosition);
        content = beforeEnd + `
  /**
   * 重置Store状态
   */
  reset: action(function() {
    // 重置Store到初始状态
    // 子类应该覆盖此方法并实现具体的重置逻辑
  }),
` + afterEnd;
      }
    }
    
    return content;
  } catch (error) {
    console.error(`标准化Store文件失败:`, error);
    return null;
  }
}

/**
 * 批量标准化Store文件
 * @param {Array<Object>} storeList - Store文件列表
 * @returns {boolean} 是否成功
 */
function batchStandardizeStores(storeList) {
  const fs = require('fs');
  let success = true;
  
  storeList.forEach(store => {
    try {
      const content = standardizeStoreFile(
        store.path,
        store.name,
        store.type,
        store.module
      );
      
      if (content) {
        fs.writeFileSync(store.path, content, 'utf8');
        console.log(`[成功] 标准化 ${store.name} Store`);
      } else {
        console.error(`[失败] 标准化 ${store.name} Store`);
        success = false;
      }
    } catch (error) {
      console.error(`[错误] 处理 ${store.name} Store 失败:`, error);
      success = false;
    }
  });
  
  return success;
}

module.exports = {
  standardizeStoreFile,
  batchStandardizeStores
}; 